<?php

namespace app\webapi\controller;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;

class ApiSms extends ApiBaseController
{

    public function getCodeByRegister_bak()
    {

    }

    public function getCodeByRegister()
    {
        $phone = Request::param('phone');
        $phone = preg_replace('/\s+/', '', $phone);
        if (!$phone) {
            $this->result_error('手机号不能为空');
        }
        if (!preg_match('/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/', $phone)) {
            $this->result_error('手机号格式错误');
        }
        $phoneExist = Db::name('user')->where('phone', $phone)->find();
        if (!empty($phoneExist)) {
            $this->result_error("该手机号已被占用");
        }
        $code = mt_rand(11111, 999999);
        $sendResult = AliSms::send_verify($phone, $code);
        if($sendResult){
//            Cache::store('redis')->set($phone, $code, 300);
            APiRedisServer::selected(1)->setex($phone,300,$code);
            $this->result_ok("验证码已发送");
        }
        $this->result_error("验证码发送失败");
    }

    public function getCodeByFindPwd()
    {
        $phone = Request::param('phone');
        $phone = preg_replace('/\s+/', '', $phone);
        if (!$phone) {
            $this->result_error('手机号不能为空');
        }
        if (!preg_match('/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/', $phone)) {
            $this->result_error('手机号格式错误');
        }
        $phoneExist = Db::name('user')->where('phone', $phone)->find();
        if (!empty($phoneExist)) {
            $this->result_error("该手机号已被占用");
        }
        $code = mt_rand(11111, 999999);
        $sendResult = AliSms::send_verify($phone, $code);
        if($sendResult){
//            Cache::store('redis')->set($phone, $code, 300);
            APiRedisServer::selected(1)->set($phone,300 ,$code);
            $this->result_ok("验证码已发送");
        }
        $this->result_error("验证码发送失败");
    }

    public static function checkSMScode($phone, $code)
    {
//        $sms = Cache::store('redis')->get($phone);
        $sms =  APiRedisServer::selected(1)->get($phone);
        return $sms === $code;
    }


}